package leetcode.code1583;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

public class Solution2 implements IDebug {

	public int unhappyFriends(int n, int[][] preferences, int[][] pairs) {
		int[][] closes = new int[n][n];
		for (int i = 0; i < n; i++) {
			int[] prefer = preferences[i];
			for (int j = 0; j < n - 1; j++) {
				closes[i][prefer[j]] = n - j;
			}
		}
		int ans = 0;
		int size = n >> 1;
		boolean[] add = new boolean[n];
		for (int i = 0; i < size; i++) {
			int[] pairi = pairs[i];
			int x = pairi[0], y = pairi[1];
			for (int j = i + 1; j < size; j++) {
				int[] pairj = pairs[j];
				int u = pairj[0], v = pairj[1];
				ans += f(x, u, y, v, closes, add);
				ans += f(x, v, y, u, closes, add);
				ans += f(y, u, x, v, closes, add);
				ans += f(y, v, x, u, closes, add);
			}
		}
		return ans;
	}

	private int f(int x, int u, int y, int v, int[][] closes, boolean[] add) {
		int ans = 0;
		if (closes[x][u] > closes[x][y] && closes[u][x] > closes[u][v]) {
			if (!add[x]) {
				add[x] = true;
				ans++;
			}
			if (!add[u]) {
				add[u] = true;
				ans++;
			}
		}
		return ans;
	}

//	6
//	[[1,4,3,2,5],[0,5,4,3,2],[3,0,1,5,4],[2,1,4,0,5],[2,1,0,3,5],[3,4,2,0,1]]
//	[[3,1],[2,0],[5,4]]
	@Override
	public void debug1() {
		HelpDebug.compare(2, this.unhappyFriends(4, HelpDebug.str2array1("[[1,2,3],[3,2,0],[3,1,0],[1,2,0]]"),
				HelpDebug.str2array1("[[0,1],[2,3]]")));
	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution2 so = new Solution2();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
